'use client';
import Image from 'next/image';
import Slider from 'react-slick';
import 'slick-carousel/slick/slick.css';
import { useEffect, useRef, useState } from 'react';
import './CategoryCarousel.scss';
import { useClientParams } from '@/hooks';
import { staticGo } from '@/utils/common';
import useResizeObserver from '@/hooks/useResizeObserver';

const CustomNextArrow = (props: any) => {
  const { className, style, onClick } = props;
  return (
    <div className={className} onClick={onClick} style={{ ...style }}>
      <div className="iconfont icon-hy_arrow-right"></div>
    </div>
  );
};
const CustomPrevArrow = (props: any) => {
  const { className, style, onClick } = props;
  return (
    <div className={className} onClick={onClick} style={{ ...style }}>
      <div className="iconfont icon-hy_arrow-left"></div>
    </div>
  );
};

const defaultImg = `data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='100' height='100'><rect width='100' height='100' fill='%23${'CFCCCF'}'/></svg>`;

const CategoryCarousel = () => {
  // const containerRef = useRef<HTMLDivElement>(null);
  const [maxThumb, setMaxThumb] = useState<number>(
    Math.min(
      6,
      Math.round(
        (Math.min(
          typeof window !== 'undefined' ? window.innerWidth : 1300,
          1300
        ) -
          92) /
          170
      )
    )
  );
  const [subCategories, setSubCategories] = useState<any[]>([]);
  const [containerRef, containerSize] = useResizeObserver();
  const [settings, setSettings] = useState<Obj>({
    slidesToShow: maxThumb,
    slidesToScroll: 1,
    swipeToSlide: true,
    infinite: subCategories?.length > maxThumb ? true : false,
    nextArrow: <CustomNextArrow />,
    prevArrow: <CustomPrevArrow />,
  });
  const resizeCallback = () => {
    const newMax = Math.min(Math.floor(containerSize.width / 170), 6);
    setMaxThumb(newMax);
    setSettings({
      ...settings,
      slidesToShow: maxThumb,
      infinite: subCategories?.length > maxThumb ? true : false,
    });
  };

  const resizeCallbackRef = useRef(resizeCallback);
  resizeCallbackRef.current = resizeCallback;

  useEffect(() => {
    subCategories?.length && resizeCallbackRef.current();
  }, [subCategories, containerSize]);

  const handleClickCategory = (e: any) => {
    // console.log(e.currentTarget.dataset);
    const dat = e.currentTarget?.dataset;
    dat && staticGo(`/categories/${dat.path}`);
  };

  const {
    basePath,
    pathname,
    queryObject,
    catePaths,
    searchParams,
    paramsObject,
    categoryObject,
    filterObject,
    categoryList,
  } = useClientParams();

  const initData = () => {
    if (basePath == 'categories') {
      const parent =
        categoryObject?.category_id ||
        Number(process.env.NEXT_PUBLIC_ROOT_CATEGORY_ID);
      const subCats = categoryList?.filter((c: any) => c.parent_id == parent);
      // console.log('🍄🍄🍄🍄==== init ====', subCats);
      subCats && setSubCategories([...subCats]);
    } else {
      setSubCategories([]);
    }
  };
  const initDataRef = useRef(initData);
  initDataRef.current = initData;

  useEffect(() => {
    initDataRef.current();
  }, [basePath, categoryObject]);

  return (
    <div className="category-carousel" ref={containerRef}>
      {basePath == 'categories' && subCategories?.length > 0 ? (
        <div className="category-carousel-wrapper">
          <Slider
            className={
              'category-carousel-slider' +
              (subCategories?.length <= maxThumb
                ? ' category-carousel-lock'
                : '')
            }
            {...settings}
          >
            {subCategories.map((subCat: any) => (
              <div
                key={subCat.category_id}
                className="category-carousel-item"
                data-path={subCat.format_paths}
                data-cid={subCat.category_id}
                onClick={handleClickCategory}
              >
                <div
                  className="category-carousel-item-img"
                  style={{ width: '100%', height: 0, paddingBottom: '100%' }}
                >
                  <Image
                    alt=""
                    key={'carousel_img_' + subCat.category_id}
                    src={subCat.image || defaultImg}
                    fill={true}
                    sizes={'180px'}
                    priority={true}
                  />
                </div>
                <div className="category-carousel-item-title">
                  {subCat.title}
                </div>
              </div>
            ))}
          </Slider>
        </div>
      ) : (
        <></>
      )}
    </div>
  );
};

export default CategoryCarousel;
